import time

import wtforms
from flask import session
from wtforms import StringField
from wtforms.validators import DataRequired, ValidationError, Length, Email
from models import UserModel
from utils.hashUtils import hashPassword


class UserLoginForm(wtforms.Form):
    # 在Flask中，表单字段的映射通常是根据字段的名称（name属性）进行的，而不是根据标签（label）
    account = StringField(label='账号：', name="account", validators=[DataRequired(message="请输入账号")])
    password = StringField(label='密码：', name='password', validators=[DataRequired(message='请输入密码')])
    imageCode = StringField(label='图片验证码：', name="imageCode", validators=[DataRequired(message='请输入验证码')])

    # 验证图片验证码
    def validate_imageCode(self, field):
        imageCode = session.get('imageCode', {})
        if field.data.upper() != imageCode.get('code').upper() or time.time() - imageCode.get('timestamp') > 60:
            # 验证码错误或已过期
            raise ValidationError(message="验证码错误或已过期！")

    # 验证账号
    def validate_account(self, field):
        user = UserModel.query.filter_by(account=field.data).first()
        if user is None:
            raise ValidationError(message='该用户不存在')

    # 验证密码
    def validate_password(self, field):
        user = UserModel.query.filter_by(account=self.account.data).first()
        if user and hashPassword(field.data) != user.password:
            raise ValidationError(message='密码不正确')


class UserRegisterForm(wtforms.Form):
    account = StringField(label='账号：', name="account",
                          validators=[
                              DataRequired(message="请输入账号"),
                              Length(min=8, max=20, message="账号长度应在8~20之间"),
                          ])
    password = StringField(label='密码：', name='password',
                           validators=[
                               DataRequired(message='请输入密码'),
                               Length(min=6, max=20, message="密码长度应在6~20之间"),
                           ])
    email = StringField(label='邮箱：', name='email',
                        validators=[
                            DataRequired(message='请输入邮箱'),
                            Email(message="邮箱格式不符合规范！"),
                        ])
    imageCode = StringField(label='图片验证码：', name="imageCode", validators=[DataRequired(message='请输入验证码')])

    def validate_account(self, field):
        user = UserModel.query.filter_by(account=field.data).first()
        if user:
            raise ValidationError(message='该用户账号已存在')

    def validate_imageCode(self, field):
        imageCode = session.get('imageCode', {})
        if field.data.upper() != imageCode.get('code').upper() or time.time() - imageCode.get('timestamp') > 60:
            # 验证码错误或已过期
            raise ValidationError(message="图片验证码错误或已过期！")


class UserMissPasswordForm(wtforms.Form):
    account = StringField(label='账号：', name="account",
                          validators=[
                              DataRequired(message="请输入账号"),
                              Length(min=8, max=20, message="账号长度应在8~20之间"),
                          ])
    newPassword = StringField(label='新密码：', name='newPassword',
                              validators=[
                                  DataRequired(message='请输入新密码'),
                                  Length(min=6, max=20, message="新密码长度应在6~20之间"),
                              ])
    emailCode = StringField(label='邮箱验证码：', name='emailCode',
                            validators=[DataRequired(message='请输入邮箱验证码')])

    def validate_newPassword(self, field):
        user = UserModel.query.filter_by(account=self.account.data).first()
        if user.password == field.data:
            raise ValidationError(message="新密码不能和老密码一样！")

    def validate_emailCode(self, field):
        emailCode = session.get('emailCode', {})
        if field.data.upper() != emailCode.get('code').upper() or time.time() - emailCode.get('timestamp') > 60:
            raise ValidationError("邮箱验证码错误或已过期！")
